//
//  YWMonitorAlarmDBManager.m
//  maintain
//
//  Created by 烟雨云渊 on 17/1/10.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWMonitorAlarmDBManager.h"
#import "YWDBTool.h"
#import "YWEquipment.h"

#import "YWMonitorAlarmModel.h"
#import "YWField.h"

@implementation YWMonitorAlarmDBManager
YWSingletonM(Manager)

- (FMDatabase*)fmdb{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue{
    return [[YWDBTool shareDBTool] dbQeue];
}
- (void)createAllMonitorAlarmTables{
    [self createMonitorAlarmTable];
    [self createMonitorFieldTable];
}

#pragma mark - 创建监控报警表
- (BOOL)createMonitorAlarmTable{
   NSString * sql = @"CREATE TABLE IF NOT EXISTS 'monitorAlarm' (monitorId integer,equipmentId varchar,title varchar,content varchar,warnTime timestamp,createTime timestamp,warnValue double);";
   return [[self fmdb] executeUpdate:sql];
}

- (BOOL)updateMonitorAlarmWithArray:(NSArray *)MonitorAlarmArray{
    if (MonitorAlarmArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockMonitorAlarmArray = MonitorAlarmArray;
    __block NSMutableArray* monitorFieldArray = [NSMutableArray array];
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockMonitorAlarmArray enumerateObjectsUsingBlock:^(YWMonitorAlarmModel* _Nonnull monitorAlarm, NSUInteger idx, BOOL* _Nonnull stop) {
            
            YWField * field = monitorAlarm.field;
            field.monitorId = monitorAlarm.monitorId;
            [monitorFieldArray addObject:monitorAlarm.field];
            
            sql = @"SELECT * FROM 'monitorAlarm' WHERE monitorId=?;";
            FMResultSet* set = [db executeQuery:sql, @(monitorAlarm.monitorId)];
            if ([set next]) {
                sql = @"UPDATE 'monitorAlarm' SET equipmentId =?,title =?,content =?,warnTime =?,createTime =?,warnValue =? WHERE monitorId =?;";
                executeResult = [db executeUpdate:sql, monitorAlarm.equipment.equipmentId,monitorAlarm.title,monitorAlarm.content,@(monitorAlarm.warnTime),@(monitorAlarm.createTime),@(monitorAlarm.warnValue),@(monitorAlarm.monitorId)];
            }
            else {
                sql = @"INSERT INTO 'monitorAlarm' (monitorId,equipmentId,title,content,warnTime,createTime,warnValue) VALUES (?, ?, ?, ?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql,@(monitorAlarm.monitorId), monitorAlarm.equipment.equipmentId,monitorAlarm.title,monitorAlarm.content,@(monitorAlarm.warnTime),@(monitorAlarm.createTime),@(monitorAlarm.warnValue)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
  //更新参数表
    [self updateMonitorFieldWithArray:monitorFieldArray];
    return executeResult;
}

- (NSArray*)monitorAlarmArrayWithPage:(NSInteger)page{
    __block NSMutableArray* monitorAlarmArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSInteger showCount = page * 10;
        NSString* sql = [NSString stringWithFormat:@"SELECT * FROM 'monitorAlarm' ORDER BY createTime DESC LIMIT %ld;", (long)showCount];
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWMonitorAlarmModel* monitorAlarm = [self monitorAlarmModelWithFMResultSet:set FMDatabase:db];
            [monitorAlarmArray addObject:monitorAlarm];
        }
        [db closeOpenResultSets];
    }];
    return monitorAlarmArray.count ? monitorAlarmArray : nil;
}

- (YWMonitorAlarmModel*)monitorAlarmModelWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db{
    YWMonitorAlarmModel * monitorAlarm = [[YWMonitorAlarmModel alloc] init];
    monitorAlarm.monitorId = [set intForColumn:@"monitorId"];
    //运行参数
    NSInteger monitorId = [set intForColumn:@"monitorId"];
    NSString* fieldSql = @"SELECT * FROM 'monitorField' WHERE monitorId =?;";
    FMResultSet* fieldSet = [db executeQuery:fieldSql, @(monitorId)];
    if ([fieldSet next]) {
        monitorAlarm.field = [self monitorFieldWithFMResultSet:fieldSet FMDatabase:db];
    }
    //设备
    NSString * equipmentId = [set stringForColumn:@"equipmentId"];
    NSString* sql = @"SELECT * FROM 'equipment' where equipmentId=?;";
    FMResultSet* newSet = [db executeQuery:sql, equipmentId];
    if ([newSet next]) {
        monitorAlarm.equipment = [[YWDBTool shareDBTool] equipmentWithFMResultSet:newSet];
    }
    monitorAlarm.title = [set stringForColumn:@"title"];
    monitorAlarm.content = [set stringForColumn:@"content"];
    monitorAlarm.warnValue = [set doubleForColumn:@"warnValue"];
    monitorAlarm.createTime = [set longLongIntForColumn:@"createTime"];
    monitorAlarm.warnTime = [set longLongIntForColumn:@"warnTime"];
    return monitorAlarm;
}

#pragma mark - 创建运行参数表

- (BOOL)createMonitorFieldTable{
    NSString * sql = @"CREATE TABLE IF NOT EXISTS 'monitorField' (monitorId integer,fieldId integer,fieldName varchar,maxFieldValue integer,minFieldValue integer)";
    return [[self fmdb] executeUpdate:sql];
}

- (BOOL)updateMonitorFieldWithArray:(NSArray*)fieldArray{
    __block BOOL executeResult = YES;
    __block NSArray* blockFieldArray = fieldArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockFieldArray enumerateObjectsUsingBlock:^(YWField* _Nonnull monitorField, NSUInteger idx, BOOL* _Nonnull stop) {
            
            sql = @"SELECT * FROM 'monitorField' WHERE monitorId=?;";
            FMResultSet* set = [db executeQuery:sql, @(monitorField.monitorId)];
            if ([set next]) {
                sql = @"UPDATE 'monitorField' SET fieldId =?,fieldName =?,maxFieldValue =?,minFieldValue =? WHERE monitorId =?;";
                executeResult = [db executeUpdate:sql,@(monitorField.fieldId),monitorField.fieldName,@(monitorField.maxFieldValue),@(monitorField.minFieldValue),@(monitorField.monitorId)];
            }
            else {
                sql = @"INSERT INTO 'monitorField' (monitorId,fieldId,fieldName,maxFieldValue,minFieldValue) VALUES (?, ?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql,@(monitorField.monitorId),@(monitorField.fieldId),monitorField.fieldName,@(monitorField.maxFieldValue),@(monitorField.minFieldValue)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    
    return executeResult;
}


- (YWField*)monitorFieldWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db{
    YWField * monitorField = [[YWField alloc] init];
    monitorField.monitorId = [set intForColumn:@"monitorId"];
    monitorField.fieldId = [set intForColumn:@"fieldId"];
    monitorField.fieldName = [set stringForColumn:@"fieldName"];
    monitorField.maxFieldValue = [set intForColumn:@"maxFieldValue"];
    monitorField.minFieldValue = [set intForColumn:@"minFieldValue"];
    return monitorField;
}

@end
